package com.zxy.supplier_system.server.controller

import com.zxy.supplier_system.server.entity.Authority
import com.zxy.supplier_system.server.service.ProcurementPaymentRecordService
import com.zxy.supplier_system.server.utils.IntIdAndName
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.domain.Sort
import org.springframework.data.web.SortDefault
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.math.BigDecimal
import java.time.OffsetDateTime

@RestController
@RequestMapping("procurements/suppliers/{supplierId}/paymentRecords")
class ProcurementSupplierPaymentRecordController(
    private val procurementPaymentRecordService: ProcurementPaymentRecordService
) {

    data class ProcurementPayRequest(
        val money: BigDecimal,
        val paidDateTime: OffsetDateTime?,
    )

    @HasAuthority(Authority.采购_账目_新增)
    @PostMapping
    fun pay(@PathVariable supplierId: Int,@RequestBody request: ProcurementPayRequest): ProcurementPayResponse {
        return procurementPaymentRecordService.pay(supplierId, request).let {
            ProcurementPayResponse(it.id!!, it.createdDateTime)
        }
    }

    data class ProcurementPayResponse(
        val id: Int,
        val createdDateTime: OffsetDateTime,
    )

    data class QueryProcurementPaymentRecordRequest(
        val endPaidDateTime: OffsetDateTime?,
    )

    @HasAuthority(Authority.采购_账目_查询)
    @GetMapping
    fun query(
        @PathVariable supplierId: Int,
        request: QueryProcurementPaymentRecordRequest,
        @SortDefault(sort = ["paidDateTime"], direction = Sort.Direction.DESC) pageable: Pageable,
    ): QueryProcurementPaymentRecordResponsePage {
        return this.procurementPaymentRecordService.query(supplierId, request, pageable)
    }

    data class QueryProcurementPaymentRecordResponse(
        val id: Int,
        val supplier: IntIdAndName,
        val createdDateTime: OffsetDateTime,
        val paidDateTime: OffsetDateTime,
        val money: BigDecimal,
    )

    class QueryProcurementPaymentRecordResponsePage(
        page: Page<QueryProcurementPaymentRecordResponse>,
        val totalPaidMoney: BigDecimal,
        val totalNeedPaidMoney: BigDecimal,
    ) : Page<QueryProcurementPaymentRecordResponse> by page

}